package com.cz.ssyx.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cz.ssyx.common.auth.AuthContextHolder;
import com.cz.ssyx.common.constant.RedisConst;
import com.cz.ssyx.common.exception.MyException;
import com.cz.ssyx.common.result.Result;
import com.cz.ssyx.common.result.ResultCodeEnum;
import com.cz.ssyx.common.utils.JwtHelper;
import com.cz.ssyx.enums.UserType;
import com.cz.ssyx.enums.user.User;
import com.cz.ssyx.user.service.UserService;
import com.cz.ssyx.user.utils.ConstantPropertiesUtil;
import com.cz.ssyx.user.utils.HttpClientUtils;
import com.cz.ssyx.vo.user.LeaderAddressVo;
import com.cz.ssyx.vo.user.UserLoginVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @descriptions:
 * @author: Joker.
 * @date: 2024/4/23 12:30
 * @version: 1.0
 */

@RestController
@RequestMapping("/api/user/weixin")
public class WeixinApiController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    //用户微信授权登录
    @GetMapping("/wxLogin/{code}")
    public Result loginWx(@PathVariable String code) {
        //小程序id
        String wxOpenAppId = ConstantPropertiesUtil.WX_OPEN_APP_ID;
        //密钥
        String wxOpenAppSecret = ConstantPropertiesUtil.WX_OPEN_APP_SECRET;

        //1.用code + openid + openSecret 请求微信接口服务
        StringBuffer url = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/jscode2session")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&js_code=%s")
                .append("&grant_type=authorization_code");
        String tokenUrl = String.format(url.toString(),
                wxOpenAppId,
                wxOpenAppSecret,
                code);
        //2.发送httpClient请求
        String result = null;
        try {
            result = HttpClientUtils.get(tokenUrl);
        } catch (Exception e) {
            throw new MyException(ResultCodeEnum.FETCH_ACCESSTOKEN_FAILD);
        }

        //3.获取session_key 和 openid
        JSONObject jsonObject = JSON.parseObject(result);
        String sessionKey = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");

        //4.根据openid查询user表
        User user = userService.getByOpenid(openid);
        //如果user为空，赋值并加入数据库
        if (user == null) {
            user = new User();
            user.setOpenId(openid);
            user.setNickName(openid);
            user.setPhotoUrl("");
            user.setUserType(UserType.USER);
            user.setIsNew(0);
            userService.save(user);
        }

        //5.根据userId查询提货点和团长信息
        LeaderAddressVo leaderAddressVo = userService.getLeaderAddressByUserId(user.getId());

        //6.用JWT工具根据userId和userName生成一个token
        String token = JwtHelper.createToken(user.getId(), user.getNickName());

        //7.返回一个更详细的UserLoginVo，放入redis，设置有效时间
        UserLoginVo userLoginVo = userService.getUserLoginVo(user.getId());
        redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX + user.getId()
                , userLoginVo, RedisConst.USERKEY_TIMEOUT, TimeUnit.DAYS);

        HashMap<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("token", token);
        map.put("leaderAddressVo", leaderAddressVo);

        return Result.ok(map);
    }

//    @PostMapping("/auth/updateUser")
//    @ApiOperation(value = "更新用户昵称与头像")
//    public Result updateUser(@RequestBody User user) {
//        User user1 = userService.getById(AuthContextHolder.getUserId());
//        //把昵称更新为微信用户
//        user1.setNickName(user.getNickName().replaceAll("[ue000-uefff]", "*"));
//        user1.setPhotoUrl(user.getPhotoUrl());
//        userService.updateById(user1);
//        return Result.ok(null);
//    }
}
